package logic

import (
	"baidu/baidurpc/baidurpc"
	"baidu/baidurpc/internal/svc"
	"baidu/models/mysql"
	"context"

	"github.com/zeromicro/go-zero/core/logx"
)

type PostListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewPostListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PostListLogic {
	return &PostListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 帖子列表展示
func (l *PostListLogic) PostList(in *baidurpc.PostListRequest) (*baidurpc.PostListResponse, error) {
	// todo: add your logic here and delete this line

	page := in.Page
	if page <= 0 {
		page = 1
	}
	pageSize := in.Size
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}
	offset := (page - 1) * pageSize
	var post []mysql.Post
	mysql.DB.Debug().Offset(int(offset)).Limit(int(pageSize)).Order("created_at desc").Find(&post)

	var postList []*baidurpc.PostList
	for _, m := range post {
		list := baidurpc.PostList{
			Title:   m.Title,
			Context: m.Context,
			UserId:  m.UserId,
			ClassId: int64(m.ID),
		}
		postList = append(postList, &list)
	}
	return &baidurpc.PostListResponse{
		List: postList,
	}, nil
}
